package main

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"fmt"
)

type RadarData struct {
	Status      string       `json:"status"`
	TargetCount uint8        `json:"target_count,omitempty"`
	AlertInfo   uint8        `json:"alert_info,omitempty"`
	Targets     []TargetData `json:"targets,omitempty"`
}

type TargetData struct {
	Angle     int64 `json:"angle"` // Changed to int64
	Distance  uint8 `json:"distance"`
	Direction uint8 `json:"direction"`
	Speed     uint8 `json:"speed"`
	Snr       uint8 `json:"snr"`
}

func parseRadarData(data []byte) (RadarData, error) {
	var radarData RadarData

	if !bytes.HasPrefix(data, []byte{0xF4, 0xF3, 0xF2, 0xF1}) || !bytes.HasSuffix(data, []byte{0xF8, 0xF7, 0xF6, 0xF5}) {
		return radarData, fmt.Errorf("invalid frame format")
	}

	data = data[4 : len(data)-4]

	dataLength := binary.LittleEndian.Uint16(data[:2])

	if len(data) != int(dataLength)+2 {
		return radarData, fmt.Errorf("incorrect data length")
	}

	if dataLength == 0 {
		radarData.Status = "No target detected"
		return radarData, nil
	}

	data = data[2:]
	radarData.Status = "Success"

	targetCount := data[0]
	radarData.TargetCount = targetCount
	radarData.AlertInfo = data[1]

	offset := 2

	for i := uint8(0); i < targetCount; i++ {
		target := TargetData{}
		angle := int64(data[offset]) - int64(0x80) // Changed to int64
		target.Angle = angle
		offset += 1
		target.Distance = data[offset]
		offset += 1
		target.Direction = data[offset]
		offset += 1
		target.Speed = data[offset]
		offset += 1
		target.Snr = data[offset]
		offset += 1
		radarData.Targets = append(radarData.Targets, target)
	}

	return radarData, nil
}

func main() {
	hexData1 := "F4F3F2F10000F8F7F6F5"
	hexData2 := "F4F3F2F1070001018002000376F8F7F6F5"
	hexData3 := "F4F3F2F1070001018002000381F8F7F6F5"

	data1, _ := hex.DecodeString(hexData1)
	result1, err := parseRadarData(data1)
	if err != nil {
		fmt.Println("Error parsing data1:", err)
	} else {
		fmt.Printf("Parsed Result 1: %#v\n", result1)
	}

	data2, _ := hex.DecodeString(hexData2)
	result2, err := parseRadarData(data2)
	if err != nil {
		fmt.Println("Error parsing data2:", err)
	} else {
		fmt.Printf("Parsed Result 2: %#v\n", result2)
	}

	data3, _ := hex.DecodeString(hexData3)
	result3, err := parseRadarData(data3)
	if err != nil {
		fmt.Println("Error parsing data3:", err)
	} else {
		fmt.Printf("Parsed Result 3: %#v\n", result3)
	}
}
